package com.huilai.platform.country_platform.repository;

import com.huilai.platform.country_platform.model.ChatLink;
import com.huilai.platform.country_platform.model.ChatList;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import java.util.List;

/**
 * 作者：洪霓
 * 日期：2023/3/27
 * 注释：
 */
public interface ChatListReposity extends JpaRepository<ChatList, Integer>, JpaSpecificationExecutor<ChatList> {

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "insert into chat_list(link_id, from_id, to_id, from_window, to_window, unread)" +
            "values(:#{#chatList.linkId},:#{#chatList.fromId}, :#{#chatList.toId},:#{#chatList.fromWindow},:#{#chatList.toWindow},:#{#chatList.unread})", nativeQuery = true)
    Integer addChatList(ChatList chatList);


    ChatList findChatListByLinkIdAndFromIdAndToId(Integer linkId, Integer fromId, Integer toId);

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "update chat_list cl set cl.unread = cl.unread + :unread where cl.link_id = :linkId and cl.from_id = :toId and cl.to_id = :fromId",nativeQuery = true)
    Integer updateUnread(Integer fromId, Integer toId, Integer unread, Integer linkId);

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "update chat_list cl set cl.unread = 0 where cl.link_id = :linkId and cl.from_id = :fromId and cl.to_id = :toId",nativeQuery = true)
    Integer clearUnread(Integer fromId, Integer toId, Integer linkId);

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "update chat_list cl set cl.from_window = :window where cl.from_id = :fromId and cl.link_id = :linkId",nativeQuery = true)
    Integer updateFromWindow(Integer linkId, Integer fromId, Integer window);

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "update chat_list cl set cl.to_window = :window where cl.to_id = :toId and cl.link_id = :linkId",nativeQuery = true)
    Integer updateToWindow(Integer linkId, Integer toId, Integer window);


}
